package project.messagestack;

import project.messagestack.utils.Logger;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.widget.RemoteViews;
import android.widget.SlidingDrawer;
import android.widget.Toast;

public class MessageStackService extends Service {
  private BackService mBackgroundWorker;
  private Thread mThread;
  private NotificationManager mNotificationManager;
  private int mStartId;
  
  private static final int mUpdateNotificationId = 5;
  public static final String UPDATE_SERVICES_NOW = "UpdateServicesNow";
 
  @Override
  public IBinder onBind(Intent intent) {
    return null;
  }

  public MessageStackService() {
    mThread = new Thread();
  }
  
  @Override
  public void onCreate() {
    super.onCreate();
    mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    mBackgroundWorker = new BackService(this);
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    prefs.registerOnSharedPreferenceChangeListener(mBackgroundWorker);
  }
  
  @Override
  public void onDestroy() {
    super.onDestroy();
    mThread.suspend();
    mThread.stop();
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    prefs.unregisterOnSharedPreferenceChangeListener(mBackgroundWorker);
    stopOngoingSynchroNotification();
  }

  public void notifyAboutNewMsgs() {
    Notification n = new Notification(R.drawable.icon, "kuniec", System.currentTimeMillis());
    Intent i = new Intent(this, message_stack.class);
    PendingIntent cI = PendingIntent.getActivity(this, 0, i, 0);
    
    n.setLatestEventInfo(this, null, null, cI);
    mNotificationManager.notify(2, n);
  }
  
  public void startOngoingSynchroNotification() {
    Notification n = new Notification(android.R.drawable.ic_popup_sync, "Refreshing", System.currentTimeMillis());
    Intent i = new Intent();
    PendingIntent pi = PendingIntent.getActivity(this, (int)System.currentTimeMillis(), i, PendingIntent.FLAG_UPDATE_CURRENT);
    RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.ongoing_notification);
    n.contentView = contentView;
    n.flags = Notification.FLAG_ONGOING_EVENT;
    n.contentIntent = pi;
    
    mNotificationManager.notify(mUpdateNotificationId, n);
  }
  
  public void stopOngoingSynchroNotification() {
    mNotificationManager.cancel(mUpdateNotificationId);
  }
  
  private void startBackgroundWorker() {
    mBackgroundWorker = new BackService(this);
    mThread = new Thread(mBackgroundWorker);
    mThread.start();
  }
  
  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
    super.onStartCommand(intent, flags, startId);
    if (intent.hasExtra(UPDATE_SERVICES_NOW)) {
      if (!mThread.isAlive()) {
         startBackgroundWorker();
      }
      mBackgroundWorker.checkAllServices(false);
    } else {
      if (!mThread.isAlive()) {
        startBackgroundWorker();
      }
    }
    mStartId = startId;
    return START_CONTINUATION_MASK;
  }
  
  private class BackService implements Runnable, OnSharedPreferenceChangeListener {
    private MessageStackService mService;
    private int mSleepTime;
    private boolean mShowNotifications;
    private SharedPreferences mPreferences;
    
    public BackService(MessageStackService s) {
      this.mService = s;
      mPreferences = PreferenceManager.getDefaultSharedPreferences(MessageStackService.this);
      mPreferences.registerOnSharedPreferenceChangeListener(this);
      mSleepTime = parseToSec(mPreferences.getString("sleepTime", "30s"));
      mShowNotifications = mPreferences.getBoolean("showNotifications", false);
    }
    
    private int parseToSec(String sleep) {
      int ret, multiplier;
      if (sleep.contains("h")) {
        sleep = sleep.replace("h", "");
        multiplier = 360;
      } else if (sleep.contains("min")) {
        sleep = sleep.replace("min", "");
        multiplier = 60;
      } else {
        sleep = sleep.replace("s", "");
        multiplier = 1;
      }
      ret = multiplier * Integer.parseInt(sleep);
      return ret;
    }
    
    synchronized public void checkAllServices(boolean showNotification) {
      if (showNotification) {
        mService.startOngoingSynchroNotification();
      }
      try {
        Thread.sleep(5000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }

      mService.stopOngoingSynchroNotification();
      
    }
    
    public void run() {
      while(true)
        try {
          //TODO: implement code wich will check new messages online
          checkAllServices(mShowNotifications);
          Thread.sleep(mSleepTime*1000);
        } catch (Exception e) {
          Logger.logError("Something went wrong " + e.getLocalizedMessage());
        }
    }

    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
                                          String key) {
      mPreferences = sharedPreferences;
      mSleepTime = parseToSec(mPreferences.getString("sleepTime", "30s"));
      mShowNotifications = mPreferences.getBoolean("showNotifications", false);
    }
    
  }
}